import axios from "axios"
import storage from "./storage"

const mock = false//是否使用mock  联调请关闭
// set config defaults when create a new instance of axios
const instance = axios.create({
  baseURL: mock ? "http://yapi.smart-xwork.cn/mock/86831" : "https://qc4nsi.fn.thelarkcloud.com",
  timeout: 8000
})

// add a request interceptor to a custom instance of axios
instance.interceptors.request.use(
  (config) => {
    // get access token
    const token = storage.getItem("token")
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    } else {
      delete config.headers.Authorization
    }
    return config
  },
  // request error
  (error) => Promise.reject(error)
)

/**
 * core function of request
 * @param {*} options request config
 */
const request = (options) => {
  options.method ??= "get"
  if (options.method.toLowerCase() === "get") {
    // uniform request parameter
    options.params = options.data
  }
  return instance(options)
}

  ;["get", "post", "put", "delete", "patch"].forEach((item) => {
    request[item] = (url, data, options) =>
      request({
        url,
        data,
        method: item,
        ...options
      })
  })
export default request
